//
//  BSAddressBookViewController.m
//  SuoSiApp
//
//  Created by zhang on 16/4/14.
//  Copyright © 2016年 Ym. All rights reserved.
//


#import "BSUIFamily+Category.h"
#import "BSAddPeronTableViewCell.h"
#import "NSString+Characters.h"
#import "BSAddressBookViewController.h"
#import "UIView+WLFrame.h"

#import <AddressBook/AddressBook.h>
@interface BSAddressBookViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSArray *personArr;
@property (nonatomic, strong) NSMutableDictionary *personDic;
@property (nonatomic, strong) UITableView *tableView;

//设置一个contactmodel的属性 用于传值
@property (nonatomic, strong) ContactModel *contactModel;

@end

@implementation BSAddressBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    _NCview = [[UIView alloc]initWithFrame:self.view.bounds];
    _NCview.backgroundColor = BSBackViewColor;
    _NCview.alpha = 0.5;
    
    self.view.backgroundColor = [UIColor colorWithRed:214.0/255 green:214.0/255 blue:214.0/255 alpha:1];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.personDic = [NSMutableDictionary dictionary];
    [self loadPerson];

    
    self.addressBookView = [[BSAddressBookView alloc]initWithFrame:CGRectMake(0, 00, kScrenWidth, kScrenHeight)];
    
    [self.addressBookView.backBT addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self addTableView];
    
    [self.view  addSubview:self.addressBookView] ;
    
    
    
    
}
- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addTableView{


    self.addressBookView.tableView.delegate = self;
    self.addressBookView.tableView.dataSource = self;
    self.addressBookView.tableView.rowHeight = 69;

    
    
    



}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return _personArr[section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _personArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSString *key = _personArr[section];
    NSArray *valueArr = _personDic[key];
    return valueArr.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 22;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"cell";
    
    BSAddPeronTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[BSAddPeronTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    [cell.addBT addTarget:self action:@selector(addPerson) forControlEvents:(UIControlEventTouchUpInside)];
    

    NSString *key= _personArr[indexPath.section];
    NSArray *personArr = _personDic[key];
    ContactModel *personModel = personArr[indexPath.row];
    
    
    cell.nameLB.text = personModel.name;
    cell.nameLB.font = [UIFont systemFontOfSize:18];
    if (personModel.phones.count != 0) {
//        如果这个人 有多个号码 显示出不能的号码 选择
        
        cell.phoneNumberLB.text = personModel.phones[0];
        cell.phoneNumberLB.font = [UIFont systemFontOfSize:15];
        

    }
      return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//    BSAddPeronTableViewCell *cell = (BSAddPeronTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    
    //    取出对应的model 传过去
    NSString *key= _personArr[indexPath.section];
    
    NSArray *personArr = _personDic[key];
    ContactModel *personModel = personArr[indexPath.row];
//    把联系人上传   穿的参数是对的 就可以 这个model 就不改了
    
//这里选择上传哪一个号码
    if (personModel.phones.count > 1) {

        self.contactModel = personModel;
        [self showViewWithPhonenumbers:personModel.phones model:personModel];
    } else {
        [PKRequestManager AddUserFamilyWithnetUrl:NetStr userID:[BSUserSGton userHandle].user_id loginName:personModel.phones[0] fName:personModel.name method:POST finish:^(NSData *data) {
            
            //        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            self.uiFamilyModel = [[BSUIFamily alloc]init];
            [_uiFamilyModel dealWithData:data];
            
            if (self.uiFamilyModel.UserID) {
                //    设置代理
                if ([_delegate respondsToSelector:@selector(passPerson:)]) {
                    [_delegate passPerson:_uiFamilyModel];
                }
            }
            [self.navigationController popViewControllerAnimated:YES];
            
        } error:^(NSError *error) {
            ;
        }];
    }
    
   
}

 //  确定添加联系人
- (void)addPerson{

    NSLog(@"就添加你了");
    
}

- (void)loadPerson{
    
    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
    
    int answer = ABAddressBookGetAuthorizationStatus();
    
    switch (answer) {
        case kABAuthorizationStatusNotDetermined:{
            NSLog(@"还没开始呢");
            
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                CFErrorRef *error1 = NULL;
                ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
                [self copyAddressBook:addressBook];
            });
            break;
        }
        case kABAuthorizationStatusRestricted:{
            
            break;
        }
        case kABAuthorizationStatusDenied:{
            
            
            
            break;
        }
        case kABAuthorizationStatusAuthorized:{
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                CFErrorRef *error1 = NULL;
                ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
                [self copyAddressBook:addressBook];
            });
            
            break;
        }
        default:
            break;
    }
    
    
}
- (void)copyAddressBook:(ABAddressBookRef)ref{
    CFIndex numberPfPeople = ABAddressBookGetPersonCount(ref);
    CFArrayRef people  =ABAddressBookCopyArrayOfAllPeople(ref);
    //   存放首字母的数组
    for (int i = 0; i < numberPfPeople; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(people, i);
        
        
        ContactModel *personModel = [[ContactModel alloc]init];
        
        
        personModel.firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        personModel.lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        
        //读取middlename
        personModel.midName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
        
        //        拼接这个人的人名字
        if (personModel.firstName && personModel.lastName) {
            personModel.name = [NSString stringWithFormat:@"%@%@",personModel.lastName, personModel.firstName];
        }else if(!personModel.firstName){
            personModel.name = personModel.lastName;
        }else{
            personModel.name = personModel.firstName;
        }
        if (!personModel.name) {
            personModel.name = personModel.organiztion;
        }
        if (personModel.nickName) {
            personModel.name =[NSString stringWithFormat:@"%@", personModel.nickName];
        }
        //        获取首字母
        NSString *firstCharacter =  [personModel.name firstCharacterOfName];
        if (firstCharacter) {
            NSMutableArray *peopleArr = [self.personDic objectForKey:firstCharacter];
            
            if (!peopleArr) {
                peopleArr = [[NSMutableArray alloc]init];
                [self.personDic setObject:peopleArr forKey:firstCharacter];
                
            }
            [peopleArr addObject:personModel];

        }
        ////        数组
        //        if (![FirnameArr containsObject:firstCharacter ]&&firstCharacter) {
        //            [FirnameArr addObject:firstCharacter];
        //        }
        
        //读取电话多值
        NSMutableArray *phoneArray = [[NSMutableArray alloc] init];
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
//            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * tempstr = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            //            NSArray *array = [NSArray arrayWithObjects:personPhoneLabel, tempstr, nil];
            
            //            只要号码 不管他是什么号码
            
            if (tempstr.length > 0) {
                [phoneArray addObject:tempstr];

            }
        }
        
//        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        
        //        每一个人名字 下面存储的号码
        if (personModel.name) {
            personModel.phones = phoneArray;
        }

    }
    
    NSLog(@"字典 %@",_personDic);
    
    _personArr = [[_personDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.addressBookView.tableView reloadData];
    });
}
- (void)showViewWithPhonenumbers:(NSArray *)numbers model:(ContactModel *)model{
    [self.view addSubview:_NCview];


    self.phoneView = [[UIView alloc]initWithFrame:CGRectMake(kScrenWidth/8, kScrenHeight/2 - kMartin80, kScrenWidth*3/4, kMartin50 * (numbers.count + 1) + numbers.count + kMartin5)];
    self.phoneView.layer.cornerRadius  = 8;
//    self.phoneView.layer.borderColor = BSGreen.CGColor;
    self.phoneView.layer.borderWidth = 1;
    self.phoneView.backgroundColor = BSBackColor;
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _phoneView.width, kMartin50)];
    lable.text = @"请选择号码";
    lable.font = [UIFont systemFontOfSize:22];
    lable.textAlignment = NSTextAlignmentCenter;
    [_phoneView addSubview:lable];
    
    for (int i = 0; i < numbers.count; i ++) {
    
        UIButton *button = BSButton;
       button.frame = CGRectMake(0 , (i + 1) * (1 + kMartin50), _phoneView.width, kMartin50);
        [button setTitle:numbers[i] forState:(UIControlStateNormal)];

        button.backgroundColor = BSWhite;
        [button setTitleColor:BSBlack forState:(UIControlStateNormal)];
        [_phoneView addSubview:button];

        [button addTarget:self action:@selector(buttonAddperson:model:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    
    
    [self.view addSubview:_phoneView];
}
- (void)buttonAddperson:(UIButton *)button model:(ContactModel*)model{
    
    model = self.contactModel;
    
//
    [_NCview removeFromSuperview];

    [PKRequestManager AddUserFamilyWithnetUrl:NetStr userID:[BSUserSGton userHandle].user_id loginName:button.currentTitle fName:model.name method:POST finish:^(NSData *data) {
        
        //        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        self.uiFamilyModel = [[BSUIFamily alloc]init];
        [_uiFamilyModel dealWithData:data];
        
        if (self.uiFamilyModel.UserID) {
            //    设置代理
            if ([_delegate respondsToSelector:@selector(passPerson:)]) {
                [_delegate passPerson:_uiFamilyModel];
            }
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    } error:^(NSError *error) {
        ;
    }];

}

- (void)aaa{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
